package cn.cl.gulimall.ware.service.impl;

import cn.cl.common.utils.R;
import cn.cl.gulimall.ware.feign.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cl.common.utils.PageUtils;
import cn.cl.common.utils.Query;

import cn.cl.gulimall.ware.dao.WareSkuDao;
import cn.cl.gulimall.ware.entity.WareSkuEntity;
import cn.cl.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
		String skuId = (String) params.get("skuId");
		if (!StringUtils.isEmpty(skuId)) {
			queryWrapper.eq("sku_id", skuId);
		}
		String wareId = (String) params.get("wareId");
		if (!StringUtils.isEmpty(wareId)) {
			queryWrapper.eq("ware_id", wareId);
		}
		IPage<WareSkuEntity> page = this.page(
				new Query<WareSkuEntity>().getPage(params),
				queryWrapper
		);
		return new PageUtils(page);
	}

	@Autowired
	private ProductService productService;

	/**
	 * 将成功采购的进行入库将成功采购的进行入库
	 */
	@Transactional
	@Override
	public void addStock(Long skuId, Long wareId, Integer skuNum) {
		// 判断如果还没有这个库存记录，则新增
		List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
		if (wareSkuEntities.size() == 0 || wareSkuEntities == null) {
			WareSkuEntity wareSkuEntity = new WareSkuEntity();
			wareSkuEntity.setSkuId(skuId);
			wareSkuEntity.setStock(skuNum);
			wareSkuEntity.setWareId(wareId);
			wareSkuEntity.setStockLocked(0);
			try {
				R r = productService.info(skuId);
				if (r.getCode() == 0) {
					Map<String, Object> map = (Map<String, Object>) r.get("skuInfo");
					wareSkuEntity.setSkuName((String) map.get("skuName"));
				}
			} catch (Exception e) {

			}
			baseMapper.insert(wareSkuEntity);
		} else {
			baseMapper.addStock(skuId, wareId, skuNum);
		}
	}
}